package com.example.sharding.dict.another;


import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.api.R;
import com.example.sharding.enerty.SysDictionary;
import com.example.sharding.service.SysDictionaryService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;

/**
 * @program: test_demo
 * @description: 字典拦截转换处理
 * @author: yanghua
 * @create: 2021-11-01 19:14
 **/

@ControllerAdvice
@AllArgsConstructor
@Slf4j
public class DictTypeSensibleAspect  implements ResponseBodyAdvice<Object> {
    @Resource
    SysDictionaryService dictDataService;


    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass) {
        return methodParameter.hasMethodAnnotation(DictTypeSensible.class)
                || methodParameter.hasMethodAnnotation(DictTypeSensibles.class);
    }

    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType
            , Class clazz, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        if (ObjectUtil.isEmpty(o)) {
            return null;
        }
        // 获取方法 注解参数
        Method method = methodParameter.getMethod();
        final String methodName = method == null ? ""
                : (method.getDeclaringClass().getSimpleName() + "." + method.getName());
        DictTypeSensible[] sensibles;
        if (methodParameter.hasMethodAnnotation(DictTypeSensible.class)) {
            DictTypeSensible sensible = methodParameter.getMethodAnnotation(DictTypeSensible.class);
            sensibles = new DictTypeSensible[]{sensible};
        } else {
            DictTypeSensibles typeSensibles = methodParameter.getMethodAnnotation(DictTypeSensibles.class);
            sensibles = typeSensibles == null ? new DictTypeSensible[]{} : typeSensibles.value();
        }
        // 处理返回值
        this.dis(o, sensibles, methodName);
        return o;
    }

    /**
     * 处理返回数据
     *
     * @param obj       对象
     * @param sensibles 字典类型
     */
    private void dis(Object obj, DictTypeSensible[] sensibles, String methodName) {
        // 处理返回类型
//        if (obj instanceof TableDataInfo) {
//            this.dis(((TableDataInfo) obj).getRows(), sensibles, methodName);
//            return;
//        }
//        if (obj instanceof AjaxResult) {
//            this.dis(((AjaxResult) obj).get(AjaxResult.DATA_TAG), sensibles, methodName);
//            return;
//        }
        if (obj instanceof R) {
            this.dis(((R) obj).getData(), sensibles, methodName);
            return;
        }
        if (obj instanceof IPage) {
            ((IPage) obj).getRecords().forEach(e -> this.dis(e, sensibles, methodName));
            return;
        }
        if (obj instanceof Iterable) {
            ((Iterable) obj).forEach(e -> this.dis(e, sensibles, methodName));
            return;
        }
        if (obj instanceof Map) {
            Map<String, Object> map = (Map<String, Object>) obj;
            for (DictTypeSensible sensible : sensibles) {
                if (!map.containsKey(sensible.value())) {
                    log.warn("--- 方法 {},字典 {} 进行忽略,不存在 ------", methodName, sensible.value());
                    continue;
                }
                Object o = map.get(sensible.value());
                if (o instanceof Iterable) {
                    this.dis(o, sensibles, methodName);
                    continue;
                }
                String code = StrUtil.isEmpty(sensible.code())
                        ? StrUtil.toUnderlineCase(sensible.value()) : sensible.code();

                log.info("第一个参数{},第二个参数{}",code,String.valueOf(o));
                //String label = dictDataService.selectDictLabel(code, String.valueOf(o));
                QueryWrapper<SysDictionary> wrapper = new QueryWrapper<>();
                wrapper.eq("dvalue",String.valueOf(o));
                wrapper.eq("type",code);
                List<SysDictionary> list = dictDataService.list(wrapper);
                if (CollectionUtils.isEmpty(list)){
                    map.put(sensible.value(), code);
                }
                //String label = dictDataService.selectDictLabel(code, String.valueOf(val));
                String label = list.get(0).getDname();
                map.put(sensible.value(), label);
            }
            return;
        }
        Class<?> clazz = obj.getClass();
        for (DictTypeSensible sensible : sensibles) {
            try {
                Field field = ReflectUtil.getField(clazz, sensible.value());
                if (field == null || !field.getType().getSimpleName().contains("String")) {
                    log.warn("--- 方法 {},字典 {} 进行忽略,不存在 || 非String类型 ------", methodName, sensible.value());
                    continue;
                }
                Object val = ReflectUtil.getFieldValue(obj, field);
                if (ObjectUtil.isEmpty(val)) {
                    continue;
                }
                String code = StrUtil.isEmpty(sensible.code())
                        ? StrUtil.toUnderlineCase(sensible.value()) : sensible.code();

                log.info("第一个参数{},第二个参数{}",code,String.valueOf(val));
                QueryWrapper<SysDictionary> wrapper = new QueryWrapper<>();
                wrapper.eq("dvalue",String.valueOf(val));
                wrapper.eq("type",code);
                List<SysDictionary> list = dictDataService.list(wrapper);
                if (CollectionUtils.isEmpty(list)){
                    ReflectUtil.setFieldValue(obj, field, code);
                }
                //String label = dictDataService.selectDictLabel(code, String.valueOf(val));
                String label = list.get(0).getDname();
                ReflectUtil.setFieldValue(obj, field, label);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
